package thread;

public class SyncDemo  {
    public static void main(String[] args){
        Table table = new Table();
        Thread first = new Thread("first"){
            @Override
            public void run(){
                while (true) {
                    int beans = table.getBeans();
                    Thread.yield();
                    System.out.println(getName() + ":" + beans);
                }
            }
        };
        Thread second = new Thread("second"){
            @Override
            public void run(){
                while (true){
                    int beans = table.getBeans();
                    Thread.yield();
                    System.out.println(getName()+":"+beans);
                }
            }
        };
first.start();
second.start();
    }

}

class Table{
    private int beans=20;
    public synchronized  int getBeans(){
        if (beans==0){
            throw new RuntimeException("没有豆子了");
        }
        Thread.yield();
        return beans--;
    }
}